#pragma once

#include <iostream>
#include <string>
#include "../public/util.hpp"
#include <cstdlib>
#include <fstream>
#include<algorithm>
#include <cassert>
#include <mutex>
#include <jsoncpp/json/json.h>
#include <vector>
#include "../public/httplib.h"
#include "../public/Log.hpp"
#include "oj_model.hpp"
#include "oj_view.hpp"
namespace ns_control
{
    using namespace httplib;
    using namespace std;
    using namespace ns_log;
    using namespace nu_util;
    using namespace ns_model;
    using namespace ns_view;
    // 负载均衡模块
    // 提供服务的主机
    class Machine
    {
    public:
        int id;//主机id；
        std::string ip;  // 编译服务的ip
        int port;        // 编译服务的端口号
        uint64_t load;   // 编译服务的负载
        std::mutex *mux; //定义一把锁
    public:
        Machine() : ip(""), port(0), load(0), mux(nullptr){};
        ~Machine(){};

    public:
        void IncLoad() // 提升主机负载
        {
            if (mux)
                mux->lock();
            ++load;
            if (mux)
                mux->unlock();
        }
        void DecLoad() // 减少负载
        {
            if (mux)
                mux->lock();
            --load;
            if (mux)
                mux->unlock();
        }
        uint64_t Load()// 获取主机负载
        {
            uint64_t _load = 0;
            if (mux)
                mux->lock();
            _load = load;
            if (mux)
                mux->unlock();
            return _load;
        }
    };
    const std::string service_machine = "./conf/service_machine.conf";

    class LoadBlance
    {
    public:
        LoadBlance()
        {
            assert(LoadConf(service_machine));
            lg.LogMessage(Info, service_machine, "加载成功\n ");
        };
        ~LoadBlance(){};
        bool LoadConf(const std::string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                lg.LogMessage(Fatal, "load加载machine失败\n");
                return false;
            }
            std::string line;
            while (getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplistString(line, &tokens, ":");
                if (tokens.size() != 3)
                {
                    lg.LogMessage(Warning, line, "切分失败\n");
                    continue;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = atoi(tokens[1].c_str());
                m.id=atoi(tokens[2].c_str());
                m.mux = new std::mutex();
                m.load = 0;
                online.push_back(machines.size());
                machines.push_back(m);
            }

            in.close();
            return true;
        }
        bool SmartChoice(int *id, Machine **m)
        {
            // 1.使用选择好的主机（更新主机负载情况）
            mtx.lock();
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                lg.LogMessage(Fatal, "所有的后端服务已离线，请运维的同学赶紧查看！\n");
                return false;
            }
            // 找到最小的负载机器
            uint64_t min_load = machines[online[0]].Load();
            *id = online[0];
            *m = &machines[online[0]];
            for (int i = 1; i < online.size(); i++)
            {
                uint64_t curr_load = machines[online[i]].Load();
                if (curr_load < min_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }

            mtx.unlock();
            return true;
        }
        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    online.erase(iter);
                    offline.push_back(which);
                    break; // 因为break的存在，不需要考虑迭代器失效的问题
                }
            }
            mtx.unlock();
        }
        void OnlineMachine()
        {
            // 当所有主机都离线的时候，我们统一上线，后面解决
             mtx.lock();
                  online.insert(online.end(),offline.begin(),offline.end());
                  offline.erase(offline.begin(),offline.end());
              mtx.unlock();
              lg.LogMessage(Info,"所有的主机已经上线\n");
        }
        void ShowMachine()
        {
            mtx.lock();
            std::cout << "当前在线主机列表:";
            for (auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout<<endl;
            std::cout << "当前离线主机列表:";
            for (auto &id : offline)
            {
                std::cout << id << " ";
            }
             std::cout<<endl;
            mtx.unlock();
        }

    private:
        std::vector<Machine> machines;// 每台主机都有他的id
        std::vector<int> online; // 所有在线主机的id
        std::vector<int> offline;// 所有离线主机的id
        std::mutex mtx; // 保证loadConf的数据安全：：加锁
    };
    class Control
    {
    public:
    void RecoveryMachine()
    {
        load_blance_.OnlineMachine();
        
    }
        bool ALLquestions(std::string *html)
        {
            bool ret = true;
            vector<struct Question> all;
            if (model_.GetAllquestions(&all))
            {
                sort(all.begin(),all.end(),[](const struct Question &q1,const struct Question &q2){
                    return atoi(q1.number.c_str())<atoi(q2.number.c_str());
                });
                // 获取所有题目成功，将所有的题目数据构建成网页
                view_.AllExpandHtml(all, html);
                return ret;
            }
            else
            {
                ret = false;
                *html = "获取题目失败，形成题目列表失败";
                return ret;
            }
        }
        bool Question(std::string &number, std::string *html)
        {
            bool ret = true;
            struct Question q;
            if (model_.GetOnequestion(number, &q))
            {
                // 获取题目成功，将题目数据构建成网页
                view_.OneExpandHtml(q, html);
                return ret;
            }
            else
            {
                ret = false;
                *html = "指定题目;" + number + "不存在！";
                return ret;
            }
        }
        void Judge(const std::string &number, const std::string in_json, std::string *out_json)
        {

            // 0.根据题目编号，拿到题目细节
            struct Question q;
            model_.GetOnequestion(number, &q);
            // 1.in—_json进行反序列化，得到题目的id，得到用户1提交源代码，
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();
            // 2.拼接用户代码+测试用例，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code +"\n"+ q.tail;
            // 测试用例都有自己的空间限制和时间限制
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);
            // 3.选择负载最低的主机，
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!load_blance_.SmartChoice(&id, &m))
                {
                    lg.LogMessage(Warning, "主机选择失败，运维同学请查看\n");
                    break;
                }
                // 4.发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                lg.LogMessage(Info,"选择主机成功主机port:%d 主机id:%d 主机负载是load:%d\n", m->port,m->id,m->Load()); // 可能有问题？？？
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json:charset=utf-8"))
                {
                    if (res->status = 200)
                    {
                        // 5.将结果给out_json;
                        *out_json = res->body;
                        m->IncLoad();
                        lg.LogMessage(Info, "请求编译和运行成功....\n");
                        break;
                    }
                    m->IncLoad();
                }
                else
                {
                    lg.LogMessage(ERror, m->ip, ":当前请求的主机 port:%d可能已经离线\n", m->port); // 可能有问题？？？
                    load_blance_.OfflineMachine(id);
                    load_blance_.ShowMachine(); //显示所有主机信息，用于检测错误
                }
            }
        }
        Control(){};
        ~Control(){};

    private:
        LoadBlance load_blance_;
        Model model_;
        View view_;
    };
}
